package org.yi.web.block;

import org.apache.commons.lang.StringUtils;
import org.yi.core.annotation.Action;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.enums.BlockTypeEnum;
import org.yi.core.enums.PostTypeEnum;
import org.yi.core.enums.SortFieldEnum;
import org.yi.web.base.BaseController;
import org.yi.web.block.entity.BlockEntity;
import org.yi.web.category.entity.CategoryEntity;

@Action(action = "/admin/block")
public class BlockController extends BaseController {
	
	public void index() {
		setAttr("list", BlockEntity.dao.getAll());
		setAttr("typeMap", BlockTypeEnum.toMap());
		setAttr("targetMap", BlockTargetEnum.toMap());
		setAttr("categoryMap", CategoryEntity.dao.getIdTitleMap());
//		setAttr("postTypeMap", PostTypeEnum.toMap());
		render("list.html");
	}
	
	public void add() {
		setAttr("typeList", BlockTypeEnum.values());
		setAttr("categoryList", CategoryEntity.dao.getAll());
		setAttr("sortFieldList", SortFieldEnum.values());
		setAttr("targetList", BlockTargetEnum.values());
		setAttr("postTypeList", PostTypeEnum.values());
		render("add.html");
	}
	
	public void save() {
		BlockEntity block = null;
		try {
			block = getModel(BlockEntity.class);
			if(BlockEntity.dao.getByName(block.getStr("name")) != null) {
				addError("文章 [" + block.getStr("name") + "] 已存在!");
				keepPara();
				render("add.html");
			} else {
				block.save();
				redirect("/admin/block");
			}
		} catch(Exception e) {
			addError("保存文章 [" + block.getStr("name") + "] 出错, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void edit() {
		String id = getPara("id");
		if(StringUtils.isNotBlank(id)) {
			setAttr("block", BlockEntity.dao.findById(id));
		}
		add();
	}
	
	public void doEdit() {
		BlockEntity block = null;
		try {
			block = getModel(BlockEntity.class);
			block.update();
			redirect("/admin/block");
		} catch(Exception e) {
			addError("编辑区块 [" + block.getStr("name") + "] 出错, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void delete() {
		String id = getPara("id");
		System.out.println(id);
		try {
			if(StringUtils.isNotBlank(id)) {
				String[] idArr = id.split(",");
				BlockEntity.dao.deleteById((Object[])idArr);
			}
		} catch (Exception e) {
			addError("删除 [" + id + "] 出错, " + e.getMessage());
			keepPara();
		} finally {
			redirect("/admin/block");
		}
	}

}
